import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';

/// 图片加载组件
class NttImageView extends StatelessWidget {
  final String imageUrl;
  final double? width;
  final double? height;
  final BoxFit? fit;
  final LoadingErrorWidgetBuilder? errorWidget;
  final AlignmentGeometry? alignment;
  final PlaceholderWidgetBuilder? placeholder;
  final Duration fadeInDuration;
  final Color? color;
  final BlendMode? colorBlendMode;
  final Map<String, String>? httpHeaders;

  String? _imageUrl = null;

  Map<String, String>? _httpHeaders = null;

  /// 当使用的是 CachedNetworkImage 时，如果需要更新则使用该方法刷新
  Function? _setState;

  NttImageView({
    super.key,
    required this.imageUrl,
    this.width,
    this.height,
    this.fit,
    this.errorWidget,
    this.alignment,
    this.placeholder,
    this.fadeInDuration = const Duration(milliseconds: 300),
    this.color,
    this.colorBlendMode,
    this.httpHeaders,
  });

  @override
  Widget build(BuildContext context) {
    if (imageUrl.startsWith('http')) {
      /// 这里需要判断是否已经替换了域名为ip
      // if(_imageUrl )
      return StatefulBuilder(
        builder:
            (BuildContext context, void Function(void Function()) setState) {
          _setState = setState;
          return CachedNetworkImage(
            imageUrl: _imageUrl ?? imageUrl,
            width: width,
            height: height,
            fit: fit,
            placeholder: placeholder ??
                (BuildContext context, String url) =>
                    const Center(child: CircularProgressIndicator()),
            errorWidget: errorWidget ??
                (BuildContext context, String url, dynamic error) =>
                    const Center(
                      child: Icon(Icons.error),
                    ),
            fadeInDuration: fadeInDuration,
            color: color,
            colorBlendMode: colorBlendMode,
            httpHeaders: httpHeaders,
          );
        },
      );
    } else if (imageUrl.startsWith('file://')) {
      /// 加载手机上的图片
      return Image.file(
        File(imageUrl),
        width: width,
        height: height,
        fit: fit,
        alignment: alignment ?? Alignment.center,
        color: color,
        colorBlendMode: colorBlendMode,
      );
    } else {
      /// 加载项目资源图片
      return Image.asset(
        imageUrl,
        width: width,
        height: height,
        fit: fit,
        alignment: alignment ?? Alignment.center,
        color: color,
        colorBlendMode: colorBlendMode,
      );
    }
  }
}
